// ===== API 工具函数 =====

import { ElNotification, ElMessage } from 'element-plus'
import request from './request.js'

// API 响应类型
export interface ApiResponse<T = any> {
  code: number | string
  data: T
  msg?: string
}

/**
 * 统一的 API 调用函数
 * @param url 请求地址
 * @param options 请求选项
 * @returns Promise<T>
 */
export const apiCall = async <T = any>(
  url: string, 
  options: {
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
    params?: Record<string, any>
    data?: Record<string, any>
    silent?: boolean // 是否静默处理错误
    showSuccess?: boolean // 是否显示成功提示
    successMsg?: string // 自定义成功提示
  } = {}
): Promise<T> => {
  const {
    method = 'GET',
    params,
    data,
    silent = false,
    showSuccess = false,
    successMsg
  } = options

  try {
    let response: ApiResponse<T>

    switch (method.toUpperCase()) {
      case 'GET':
        response = await request.get(url, { params })
        break
      case 'POST':
        response = await request.post(url, data, { params })
        break
      case 'PUT':
        response = await request.put(url, data, { params })
        break
      case 'DELETE':
        response = await request.delete(url, { params })
        break
      default:
        throw new Error(`Unsupported method: ${method}`)
    }

    // 检查响应状态
    if (response.code === 200 || response.code === '200') {
      if (showSuccess) {
        ElMessage.success(successMsg || '操作成功')
      }
      return response.data
    } else {
      throw new Error(response.msg || '请求失败')
    }
  } catch (error: any) {
    if (!silent) {
      console.error(`API Error [${method} ${url}]:`, error)
      
      // 显示错误通知
      ElNotification({
        title: '请求失败',
        message: error.message || '网络错误，请稍后重试',
        type: 'error',
        duration: 3000
      })
    }
    
    throw error
  }
}

/**
 * GET 请求封装
 */
export const get = <T = any>(url: string, params?: Record<string, any>, options?: { silent?: boolean }) =>
  apiCall<T>(url, { method: 'GET', params, ...options })

/**
 * POST 请求封装
 */
export const post = <T = any>(
  url: string, 
  data?: Record<string, any>, 
  options?: { 
    params?: Record<string, any>
    silent?: boolean
    showSuccess?: boolean
    successMsg?: string
  }
) => apiCall<T>(url, { method: 'POST', data, ...options })

/**
 * PUT 请求封装
 */
export const put = <T = any>(
  url: string, 
  data?: Record<string, any>, 
  options?: { 
    params?: Record<string, any>
    silent?: boolean
    showSuccess?: boolean
    successMsg?: string
  }
) => apiCall<T>(url, { method: 'PUT', data, ...options })

/**
 * DELETE 请求封装
 */
export const del = <T = any>(url: string, params?: Record<string, any>, options?: { silent?: boolean }) =>
  apiCall<T>(url, { method: 'DELETE', params, ...options })

// 常用 API 端点常量
export const API_ENDPOINTS = {
  // 网站信息
  WEBSITE: '/website/getWebsite',
  
  // 文章相关
  ARTICLES: '/blog/getArticles',
  ARTICLE_DETAIL: '/blog/getArticleById',
  ARTICLE_LIKE: '/blog/like',
  ARTICLE_VIEWS: '/blog/views',
  NEWS_ARTICLES: '/blog/getNewsArticle',
  
  // 分类和标签
  CATEGORIES: '/category/getCategories',
  TAGS: '/tag/getTags',
  
  // 评论相关
  COMMENTS: '/comment/getComments',
  COMMENT_ADD: '/comment/add',
  COMMENT_LIKE: '/comment/like',
  
  // 搜索
  SEARCH: '/search',
  
  // 归档
  ARCHIVES: '/blog/getArchives',
  
  // 相册
  ALBUMS: '/album/getAlbums',
  PHOTOS: '/album/getPhotos',
  
  // 关于页面
  ABOUT: '/about/getInfo',
  
  // 留言
  MESSAGES: '/message/getMessages',
  MESSAGE_ADD: '/message/add',
  
  // 友链
  LINKS: '/link/getLinks'
} as const

// 业务 API 函数
export const websiteApi = {
  getInfo: () => get(API_ENDPOINTS.WEBSITE),
}

export const articleApi = {
  getList: (params: Record<string, any>) => get(API_ENDPOINTS.ARTICLES, params),
  getById: (id: string | number) => get(`${API_ENDPOINTS.ARTICLE_DETAIL}/${id}`),
  getNews: () => get(API_ENDPOINTS.NEWS_ARTICLES),
  like: (id: string | number) => post(`${API_ENDPOINTS.ARTICLE_LIKE}/${id}`, {}, { showSuccess: true, successMsg: '点赞成功' }),
  addView: (id: string | number) => post(`${API_ENDPOINTS.ARTICLE_VIEWS}/${id}`, {}, { silent: true }),
}

export const categoryApi = {
  getList: () => get(API_ENDPOINTS.CATEGORIES),
}

export const tagApi = {
  getList: () => get(API_ENDPOINTS.TAGS),
}

export const commentApi = {
  getList: (blogId: string | number, params?: Record<string, any>) => 
    get(`${API_ENDPOINTS.COMMENTS}/${blogId}`, params),
  add: (data: Record<string, any>) => 
    post(API_ENDPOINTS.COMMENT_ADD, data, { showSuccess: true, successMsg: '评论成功' }),
  like: (id: string | number) => 
    post(`${API_ENDPOINTS.COMMENT_LIKE}/${id}`, {}, { showSuccess: true, successMsg: '点赞成功' }),
}

export const searchApi = {
  search: (keyword: string, params?: Record<string, any>) => 
    get(API_ENDPOINTS.SEARCH, { keyword, ...params }),
}

export const albumApi = {
  getList: () => get(API_ENDPOINTS.ALBUMS),
  getPhotos: (albumId: string | number) => get(`${API_ENDPOINTS.PHOTOS}/${albumId}`),
}

// 错误处理工具
export const handleApiError = (error: any, customMessage?: string) => {
  console.error('API Error:', error)
  
  ElNotification({
    title: '操作失败',
    message: customMessage || error.message || '请求失败，请稍后重试',
    type: 'error',
    duration: 3000
  })
}

// 请求重试工具
export const retryRequest = async <T>(
  requestFn: () => Promise<T>,
  maxRetries: number = 3,
  delay: number = 1000
): Promise<T> => {
  let lastError: any
  
  for (let i = 0; i <= maxRetries; i++) {
    try {
      return await requestFn()
    } catch (error) {
      lastError = error
      
      if (i < maxRetries) {
        console.warn(`Request failed, retrying in ${delay}ms... (${i + 1}/${maxRetries})`)
        await new Promise(resolve => setTimeout(resolve, delay))
        delay *= 2 // 指数退避
      }
    }
  }
  
  throw lastError
}